package com.mall507.comn.tools;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import com.alibaba.android.arouter.launcher.ARouter;
import com.hzh.frame.comn.callback.HttpCallBack;
import com.hzh.frame.core.BaseSP;
import com.hzh.frame.core.HttpFrame.BaseHttp;
import com.hzh.frame.util.Util;
import com.hzh.frame.widget.xdialog.XDialogSubmit;
import com.mall507.comn.model.Ader;
import com.mall507.comn.model.User;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @version 1.0
 * @date 2018/4/12
 */

public class UserTools {
    public static final String TAG = "UserTools --- > ";
    
    private static UserTools _instance;
    private static User mUser;
    private static Ader mAder;
    
    public static UserTools getInstance(){
        synchronized (UserTools.class){
            if(_instance==null){
                _instance=new UserTools();
            }
            return _instance;
        }
    }

    /**
     * 获取用户是否登录
     */
    public boolean getIsLogin(){
        return BaseSP.getInstance().getBoolean("login", false);
    }
    

    /**
     * 获取用户信息
     */
    public User getUser(){
        synchronized (User.class){
            if(getIsLogin()){
                //已登录
                mUser=new Select().from(User.class).executeSingle();
            }
            return mUser == null ? new User() : mUser;
        }
    }

    /**
     * 获取用户ID
     */
    public String getUserId(){
        return getUser().getUserid();
    }


    /**
     * 登录回调接口
     * */
    public interface LoginCallBack{
        void showMsg(String msg);//提示信息
        void loginComplete();//登录完成
        void toRelationPhone(User user);//去关联
        void userInfoComplete();//用户信息获取完成
    }
    
    /**
     * 登录 | 第一步
     */
    public void login(User user, Activity activity,LoginCallBack callBack){
        JSONObject params = new JSONObject();
        if ("0" == user.getLoginType()) {//帐号密码登录
            try {
                params.put("phone", user.getPhone().trim());
                params.put("password", user.getPassword().trim());
                params.put("source", user.getLoginType());//0为手机号码,1为微信,2为QQ,3为新浪
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        } else {//其他方式登录
            try {
                params.put("openId", user.getOpenId());
                params.put("nickName", user.getNickName());
                params.put("userIcon", user.getHead());
                params.put("source", user.getLoginType());//0为手机号码,1为微信,2为QQ,3为新浪
                if(user.getSex() != null){//获取到性别信息
                    params.put("userGender", user.getSex());
                }
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        }
        BaseHttp.getInstance().query("login/login", params, new LoginHttpCallBack(user,callBack).setSubmit(new XDialogSubmit(activity).alert()));
    }


    /**
     * 登录请求回调 | 第二步
     * */
    class LoginHttpCallBack extends HttpCallBack {

        User mUser;
        LoginCallBack mLoginCallBack;

        public LoginHttpCallBack(User user,LoginCallBack callBack){
            this.mUser=user;
            this.mLoginCallBack=callBack;
        }
        
        @Override
        public void onSuccess(JSONObject response) {
            if (200 == response.optInt("code")) {
                JSONObject obj = response.optJSONObject("data");
                BaseSP.getInstance().put("login", true);
                BaseSP.getInstance().put("token", obj.optString("token"));

                //获取用户信息
                if ("0" == mUser.getLoginType()) {//帐号密码登录
                    UserTools.getInstance().loadUserInfo(mUser.getPassword().trim(), mUser.getLoginType(),mLoginCallBack);
                }else{//其他方式登录
                    UserTools.getInstance().loadUserInfo("", mUser.getLoginType(),mLoginCallBack);
                }
                mLoginCallBack.loginComplete();//登录完成
            } else
            if(300 == response.optInt("code")){//其他方式登录 | 未绑定手机号
                mLoginCallBack.toRelationPhone(mUser);
            }else{
                mLoginCallBack.showMsg(response.optString("msg"));
            }
        }
    }
    

    /**
     * 获取用户信息 | 第三步
     * @param password 密码
     * @param loginType 第三方登录类型 0为手机号码,1为微信,2为QQ,3为新浪
     * */
    public void loadUserInfo(final String password, final String loginType, final LoginCallBack callBack){
        BaseHttp.getInstance().query("member/getInfo", new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject response) {
                if (200 == response.optInt("code")) {
                    JSONObject userJson=response.optJSONObject("data");
                    new Delete().from(User.class).execute();//清空用户信息
                    User user = new User()
                            .setUserid(userJson.optString("id"))
                            .setPhone(userJson.optString("phone"))
                            .setAcount(userJson.optString("username"))
                            .setPassword(password)
                            .setHead(userJson.optString("head_img"))
                            .setNickName(userJson.optString("nickname"))
                            .setLoginType(loginType)
                            .setOpenId(userJson.optString("openid"))
                            .setPersonalSign(userJson.optString("sign"))
                            .setSex(userJson.optString("sex"));
                    user.save();
                    BaseSP.getInstance().put("userId", user.getUserid());
                    mUser=user;
                    callBack.userInfoComplete();
                }else{
                    callBack.showMsg(response.optString("msg"));
                }
            }
        });
    }
    
    /**
     * 刷新用户信息
     * */
    public void refresh(){
        this.mUser=mUser=new Select().from(User.class).executeSingle();
    }
    
    /**
     * 清空用户信息
     * */
    public void clear(){
        new Delete().from(User.class).execute();
        BaseSP.getInstance().put("login", false);
        BaseSP.getInstance().put("userId", "");
        BaseSP.getInstance().put("token","");
        mUser=null;
    }

    /**
     * 更新用户信息
     * */
    public void updUser(User user){
        user.save();
        if (user.getUserid() != null && user.getUserid().length() > 0){
            BaseSP.getInstance().put("userId", user.getUserid());
        }
        mUser=user;
    }

    
}
